
#Using code and ideas from:
#http://www.astro.washington.edu/courses/astro480/IRAF/
#http://www.astronomy.pomona.edu/astro101/iraf.phot.html
#http://stsdas.stsci.edu/pyraf/doc.old/pyraf_tutorial/StandardPython.html
#http://www.lancesimms.com/programs/Python/pyraf/CenterStarsInteractively.py


#------------
#To setup, specify:bias, flat
#-----------
from pyraf import iraf
#from time import wait
from easy_phot_params import *
import os,sys
import easy_phot

files = glob.glob(image_dir+rootstr+"*")
refname=files[0]

iraf.set(stdimage= 'imt4096')

iraf.images()
iraf.imutil()

iraf.noao(_doprint=0)      # load noao
iraf.digiphot(_doprint=0) # load digiphot
iraf.apphot(_doprint=0)   # load apphot
                          #iraf.disp(refname,1)
iraf.imred(_doprint=0)
iraf.ccdred(_doprint=0)

print("Make sure DS9 is running. Tested with SAOImage 6.1 in OS-X")

print("Did you specify image director, bias and flat field file names in eas_phot_params.py?")
msg = 'enter y reduce CCD data, otherwise this program will exit'
shall = True if raw_input("%s (y/any key) " % msg).lower() == 'y' else False
if shall:
    msg = 'Do you want select a new set of stars for alignment and overwrite coords.txt file if it exists?'

    shallover = True if raw_input("%s (y/any key) " % msg).lower() == 'y' else False
    if shallover:
        #delete old coordnate file and launch imexam to get alignment coordinates:
        try:
            os.remove('coords.txt')
        except Exception, err:
            print(err)

        try:
            print("use the letter a to select stars for alignmenty and q to quit\n Select star of INTEREST FIRST")
            iraf.imexam(refname,Stdout='coords.txt')#,Sterr='errs.txt')
        except Exception,e:
            print(e) 
else:
    #quit otherwise
    sys.exit(0)
    
#delete old coordnate file and launch imexam to get alignment coordinates:
'''try:
    os.remove('coords.txt')
except Exception, err:
    print(err)

try:
    print("use the letter a to select stars for alignment and photometry and q to quit\n Select star of INTEREST FIRST")
    iraf.imexam(refname,Stdout='coords.txt')#,Sterr='errs.txt')

except Exception,e:
    iraf.disp(refname)
    print(e)
'''
    

'''Flatten before aligning, because the dark and flat field subtracted are in image coordinates.

'''
    
flatten = True if raw_input("reduce CCD images (flat field, subtract bias, (y/any key) ").lower() == 'y' else False

if flatten:
    for im in files:
        print('reducing:'+im)
        print("this is over-simplified flat fielding, for example in demo data, \n          there is some extra dust at the edges and large scale intensity variations,\n           to correct that need to twilight flat the dome flat.")
        if (bias) and (flat):
            try:
                iraf.ccdproc(images = im,flatcor='yes',zero=bias,flat=flat,output=im+flatstr)
            except Exception,err:
                print(err)


files = glob.glob(image_dir+rootstr+'*'+flatstr+'*')

for im in files:
    print('aligning:'+im)
    #run imalign on the list
    try:
        iraf.imalign(im, reference=refname, coords='coords.txt', bigbox=25, boxsize=15, trimim='yes', output=im+alignstr,niterate=25)
        print("A")
    except Exception,err:        
        print(err)

print("Image Reduction and alignment complete.")

